package com.example.italkapp2.controller.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.italkapp2.R;
import com.example.italkapp2.controller.activity.ChatActivity;
import com.example.italkapp2.model.Model;
import com.example.italkapp2.model.bean.UserInfo;
import com.example.italkapp2.model.dao.ContactTableDao;
import com.example.italkapp2.model.dao.UserAccountDao;
import com.example.italkapp2.model.db.DBManager;
import com.example.italkapp2.utils.myParse;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseIM;
import com.hyphenate.easeui.constants.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.manager.EaseSystemMsgManager;
import com.hyphenate.easeui.modules.contact.EaseContactListFragment;
import com.hyphenate.easeui.modules.conversation.EaseConversationListFragment;
import com.hyphenate.easeui.provider.EaseUserProfileProvider;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseImageView;
import com.hyphenate.easeui.widget.EaseTitleBar;

import java.util.List;

//会话列表页面
public class ChatFragment extends EaseConversationListFragment {


    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        //设置头像样式：0为默认，1为圆形，2为方形(设置方形时，需要配合设置avatarRadius，默认的avatarRadius为50dp)
        conversationListLayout.setAvatarShapeType(EaseImageView.ShapeType.ROUND);
        Model.getInstance().getDbManager().getContactTableDao();
        //监听会话消息
        EMClient.getInstance().chatManager().addMessageListener(emMessageListener);

        EaseIM.getInstance().setUserProvider(new EaseUserProfileProvider() {
            @Override
            public EaseUser getUser(String username) {
                // 根据username，从数据库中或者内存中取出之前保存的用户信息，如从数据库中取出的用户对象为DemoUserBean
                EaseUser user = new EaseUser(username);
                // 设置用户昵称
                user.setNickname(username);
                // 设置用户头像
                String url;
                // 如果是当前用户，需要特殊处理
                if (username.equals(EMClient.getInstance().getCurrentUser())) {
                    // 用户名字为字符串
                    if (EMClient.getInstance().getCurrentUser().charAt(0) < '0'
                            || EMClient.getInstance().getCurrentUser().charAt(0) > '9') {
                        url = "https://picsum.photos/id/" +
                                myParse.getInstance().paraseIntInRange(EMClient.getInstance().getCurrentUser(), 1000) + "/200";
                    } else {
                        url = "https://picsum.photos/id/" + EMClient.getInstance().getCurrentUser() + "/200";
                    }
                    user.setAvatar(url);
                    //最后返回构建的EaseUser对象
                    return user;
                } else if (username.length() >= 15) {
                    user.setNickname(getGroupName(username));
                    return user;
                }
                ContactTableDao contactTableDao = Model.getInstance().getDbManager().getContactTableDao();
                UserInfo userInfo = contactTableDao.getContactByHx(username);
                //设置头像地址
                user.setAvatar(userInfo.getPhoto().toString());
                //最后返回构建的EaseUser对象
                return user;
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        super.onItemClick(view, position);
        Object item = conversationListLayout.getItem(position).getInfo();
        if(item instanceof EMConversation) {
            if(EaseSystemMsgManager.getInstance().isSystemConversation((EMConversation) item)) {
                Intent intent = new Intent(mContext, ChatActivity.class);
                mContext.startActivity(intent);
            }else {
                Intent intent = new Intent(mContext, ChatActivity.class);
                intent.putExtra("titleName",((EMConversation)item).conversationId());
                intent.putExtra(EaseConstant.EXTRA_CONVERSATION_ID, ((EMConversation)item).conversationId());
                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseCommonUtils.getChatType((EMConversation) item));
                mContext.startActivity(intent);
            }
        }
        onRefresh();
    }

    private EMMessageListener emMessageListener=new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //设置数据
            EaseIM.getInstance().getNotifier().notify(messages);

            onRefresh();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {

        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {

        }
    };

    public static String getGroupName(String groupId) {
        EMGroup group = EMClient.getInstance().groupManager().getGroup(groupId);
        if(group == null) {
            return groupId;
        }
        return TextUtils.isEmpty(group.getGroupName()) ? groupId : group.getGroupName();
    }
}